/**
 * 
 */
package com.primestone.cim.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author cesar.mateus
 * Oct 30, 2013 2:20:54 AM
 * CompressUtil.java
 * CIMUtil
 * 
 */
public class CompressUtil {
	public static void main(String[] args) {
		try {
			zip(new File("TextFiles.zip"), new File("sample.txt"));
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
	
	/**
	 * 
	 * @param zipFile
	 * @param inputFile
	 * @throws IOException
	 */
	public static void zipFile(File zipFile, File inputFile) throws IOException {
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        FileInputStream fis = null;
        try {
            fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(new BufferedOutputStream(fos));
            fis = new FileInputStream(inputFile);
            ZipEntry ze = new ZipEntry(inputFile.getName());
            //System.out.println("Zipping the file: "+input.getName());
            zos.putNextEntry(ze);
            byte[] byteBuffer = new byte[4*1024];
            int size = 0;
            while((size = fis.read(byteBuffer)) != -1){
                zos.write(byteBuffer, 0, size);
            }
            zos.closeEntry();
            zos.flush();
            zos.close();
        } finally{
            try{
                if(fos != null) fos.close();
                if(fis != null) fis.close();
            } catch(Exception ex){
                 // Ignore.
            }
        }
    }

	/**
	 * @param zip
	 * @param file
	 * @throws IOException
	 */
	public static void zip(File zip, File file) throws IOException {
		ZipOutputStream zos = null;
		OutputStream os = null;
		try {
			os = new FileOutputStream(zip);
			String name = file.getName();
			zos = new ZipOutputStream(os);

			ZipEntry entry = new ZipEntry(name);
			zos.putNextEntry(entry);

			FileInputStream fis = null;
			try {
				fis = new FileInputStream(file);
				byte[] byteBuffer = new byte[1024];
				int bytesRead = -1;
				while ((bytesRead = fis.read(byteBuffer)) != -1) {
					zos.write(byteBuffer, 0, bytesRead);
				}
				zos.flush();
			} finally {
				try {
					if (fis != null) {
						fis.close();
					}
				} catch (Exception e) {
					// Ignore
				}
			}
			zos.closeEntry();

			zos.flush();
		} finally {
			try {
				if (zos != null) {
					zos.close();
				}
				if (os != null) {
					os.close();
				}
			} catch (Exception e) {
				// Ignore
			}
		}
	}
}
